from django.shortcuts import render, redirect
from app01 import models
from app01.utils.bootstrapForm import BootstrapModelForm


def user_list(request):
    """用户列表"""
    users = models.UserInfo.objects.all()
    return render(request, 'user_list.html', {'users': users})


class UserModelForm(BootstrapModelForm):
    """创建UserInfo模型对应的ModelForm以供前端使用"""

    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'gender', 'account', 'create_time', 'depart']


def user_modelform_add(request):
    """使用modelForm添加用户"""
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_modelForm_add.html', {'form': form})

    # 接收POST提交的数据，进行数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据有效则通过form中定义的model保存到数据库
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_modelForm_add.html', {'form': form})


def user_modelform_edit(request, nid):
    """使用modelForm编辑用户"""
    row_object = models.UserInfo.objects.filter(id=nid).first()
    # 以GET方式请求页面
    if request.method == "GET":
        form = UserModelForm(instance=row_object)
        return render(request, 'user_modelForm_edit.html', {'form': form})
    # 以POST提交编辑后的数据
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_modelForm_edit.html', {'form': form})


def user_modelform_delete(request, nid):
    """使用modelForm删除用户"""
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')


# 添加用户
def user_add(request):
    if request.method == 'GET':
        return render(request, 'user_add.html')
    user = request.POST['user']
    password = request.POST['pass']
    age = request.POST['age']
    models.UserInfo.objects.create(name=user, password=password, age=age)
    return redirect('/user/list/')


def user_delete(request):
    """删除用户"""
    nid = request.GET.get('nid')
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')
